﻿package Naruto.Frames {
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.MouseEvent;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.display.MovieClip; 	//导入影片剪辑类
	import Naruto.Bloods.*;
	import Naruto.*;
		
	public class Frame1 extends Sprite{
		private var _appStart:Start;	//游戏开始的主类,用于调用主类中的剧务函数
		
		private var _status:Status;		//用于引用人物状态（全局）
		
		private var _stage:Stage;		//舞台
		
		private var eventSprite:Sprite; //事件精灵
	
		public var scene1:Scene1;		//第一个场景 
		
		public var me:aNaruto;			//主角
		private var _blood:Blood;		//主角血条类
		private var _health:int;		//血量
		private var _ckl:int;			//查克拉
		
		private var _item:Item = null;	//道具框
		private var _item1:Item1 = null;//道具框1(苦无)
		private var _item4:Item4 = null;//道具框4(螺旋丸)
		
		public var enemys:Array;		//敌人队列
		
		public var flyshittest:ObjectHitTest;	//飞镖碰撞检测类
		public var flystestobj:Array;			//飞镖碰撞队列（对敌人）
		public var flyshurtmeobj:Array;  		//飞镖碰撞队列 (对主角)
		public var enemystestobj:Array; 		//敌人碰撞队列
		
		
		public var creataitimer:Timer;		//按时间创建敌人
		public var creatAiAttackTimer:Timer;//创建Ai攻击
		public var creatAshtimer:Timer; 	//清道夫计时器
		
		public var enemynum:int;		//创建敌人数量
		
		public var meattack:Attack;
		
		private var flag:int; 			//标志是否可发下一个镖		
		private var keycode:Array;		//记载按下键盘的按键
		
		private var _isEnd:Boolean;		//记载本幕是否结束
		
		public function Frame1(aStatus:Status, stage:Stage, appStart:Start){
			this._stage = stage;
			this._status = aStatus;
			this._appStart = appStart;
			init();
		}
		private function init():void{
			
			flyshittest = new ObjectHitTest();	//初始化碰撞检测
			enemystestobj = new Array();        //初始化敌人碰撞队列
			flystestobj = new Array();			//初始化敌人受飞镖攻击碰撞队列
			flyshurtmeobj = new Array();        //初始化主角受飞镖攻击碰撞队列
			
			scene1 = new Scene1();				//加载第一个场景
			this._stage.addChildAt(scene1,0);
			
			me = new aNaruto(this._status);		//初始化主角
			me.setpos(this._stage);				//初始化位置
			me.setLevel(this._status.getLevel());	//初始化等级
			this._stage.addChild(me.getme());
			
			this._blood = new Blood(this._stage);	//初始化血条
			this._health = this._status.getHealth();//初始化血量
			this._blood.changeHealth(this._health);	//设置血条宽度
			
			this._ckl = this._status.getCkl();		//初始化查克拉量
			this._blood.changeCkl(this._ckl);	//设置查克拉宽度
			
			creatItem();		//创建道具框
			
			creatEnemys();						//创建敌人
			creatAiAttack();					//敌人攻击
			
			flyshittest.getflystestobj(enemystestobj,me,flystestobj);		//开始飞镖碰撞检测，参数(敌人队列，伤敌飞镖队列，伤我飞镖队列)
			this._stage.addEventListener(Event.ENTER_FRAME,onEnterFrame);
			
			creatAshman();						//创建清道夫
			
			flag = 0;
			keycode = [0];
			this._isEnd = false;
			
			this._stage.addEventListener(MouseEvent.MOUSE_DOWN,onMouseDown);
			//this._stage.addEventListener(MouseEvent.MOUSE_UP,onMouseUp);
			this._stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyboardEvent);
			this._stage.addEventListener(KeyboardEvent.KEY_UP,onKeyboardEvent);
		}
		
		//加载道具框
		public function creatItem():void{
			switch(this._status.getCurrentItem()){
				case 0:{this._item = new Item();
						this._item.x = 800;
						this._item.y = 750;
						this._stage.addChild(_item);break;}
				case 1:{this._item1 = new Item1();
						this._item1.x = 800;
						this._item1.y = 750;
						this._stage.addChild(_item1);break;}
				default:return;
			}		
		}
		
		//改变道具
		public function changeItem() {
			//trace(this._status.getCurrentItem());
			switch(this._status.getCurrentItem()){
				case 0:{
						if( (this._item!=null) && (this._stage.contains(this._item)) )	//已经是当前道具
							break;									
						else{															//非当前道具
							if( (this._item1!=null) && (this._stage.contains(this._item1)) ){		//1:苦无
								this._stage.removeChild(this._item1);
							}else if( (this._item4!=null) && (this._stage.contains(this._item4)) ){	//4：螺旋丸
								this._stage.removeChild(this._item4);
							}
							this._item = new Item();
							this._item.x = 800;
							this._item.y = 750;
							this._stage.addChild(_item);
							break;
						}
					}
				case 1:{
						if( (this._item1!=null) && (this._stage.contains(this._item1)) )
							break;										
						else{											
							if( (this._item!=null) && (this._stage.contains(this._item)) ){
								this._stage.removeChild(this._item);
							}else if( (this._item4!=null) && (this._stage.contains(this._item4)) ){	
								this._stage.removeChild(this._item4);
							}
							this._item1 = new Item1();
							this._item1.x = 800;
							this._item1.y = 750;
							this._stage.addChild(_item1);
							break;
						}
					}
				case 4:{						
						if( (this._item4!=null) && (this._stage.contains(this._item4)) )
							break;										
						else{											
							if( (this._item!=null) && (this._stage.contains(this._item)) ){
								this._stage.removeChild(this._item);
							}else if( (this._item1!=null) && (this._stage.contains(this._item1)) ){	
								this._stage.removeChild(this._item1);
							}
							this._item4 = new Item4();
							this._item4.x = 800;
							this._item4.y = 750;
							this._stage.addChild(_item4);
							break;
						}
					}
				default:return;
			}
		}
		
		public function creatEnemys():void{
			enemynum = 0;
			enemys = new Array();
			for(var i=0;i<4;i++){
				enemys[i] = new aGenin(this._stage);		//开始布置下忍*4
			}
			creataitimer = new Timer(1000);
			creataitimer.addEventListener(TimerEvent.TIMER,CreatAI);
			creataitimer.start();
		}
		
		//创建敌人
		public function CreatAI(event:Event):void{
			if( enemynum < 4 ){
				this._stage.addChild(enemys[enemynum].getme());
				enemystestobj.push(enemys[enemynum].getme());	//将新建敌人加入敌人碰撞队列
				enemynum += 1;
			}
			else{
				creataitimer.removeEventListener(TimerEvent.TIMER,CreatAI);
				creataitimer.stop();
			}			
		}
		
		//创建AI攻击
		public function creatAiAttack(){
			creatAiAttackTimer = new Timer(3000);
			creatAiAttackTimer.addEventListener(TimerEvent.TIMER,aiAttack);	//敌人开始攻击
			creatAiAttackTimer.start();
		}
		
		//Ai攻击
		public function aiAttack(event:Event):void{
			//敌人攻击
			for(var m=0;m<4;m++){
				if(enemys[m]){
					flyshurtmeobj.push(enemys[m].getAttack().AiStartAttack(this._stage,enemys[m].getme(),me.getme()));	//敌人攻击
				}
			}
		}
		
		//创建清道夫
		public function creatAshman(){
			creatAshtimer = new Timer(1000);
			creatAshtimer.addEventListener(TimerEvent.TIMER,Ashman);
			creatAshtimer.start();			
		}
		
		//清道夫
		public function Ashman(event:Event){
			//移除死亡者,将敌人在碰撞队列的位置置空（不能用splice删除，因为会导致数组错位问题），再从舞台移除
			var allClear:Boolean = true;	//是否还有敌人存在，影响本幕是否就结束
			for(var i=0;i<enemys.length;i++){
				if(enemys[i]!=null){
					allClear = false;
					//trace("enemys["+i+"].getStatus=" + enemys[i].getStatus());
					if(enemys[i].getStatus()==0){	//0:最高级别伤害（死亡）
						enemystestobj[i] = null;	//从碰撞队列移除
						enemys[i].removeGenin();
						enemys[i]=null;
					}
				}				
			}
			this._isEnd = allClear;
			
			if(this._isEnd == true){
				//移除所有监听器
				this._stage.removeEventListener(Event.ENTER_FRAME,onEnterFrame);
				this._stage.removeEventListener(MouseEvent.MOUSE_DOWN,onMouseDown);
				this._stage.removeEventListener(KeyboardEvent.KEY_DOWN,onKeyboardEvent);
				this._stage.removeEventListener(KeyboardEvent.KEY_UP,onKeyboardEvent);
				
				//移除所有计时器
				creataitimer = null;
				creatAiAttackTimer.stop();
				creatAiAttackTimer = null;
				creatAshtimer.stop();
				
				//删除所有舞台对象
				//trace(this._stage.numChildren);
				
				var len:uint = this._stage.numChildren;
				while(len>0) {
				    this._stage.removeChildAt(0);
					len--;
				}
				//trace(this._stage.numChildren);
				
				//保存角色状态
				//this._status.setLevel();
				this._status.setHealth(this._blood.getHealth());
				this._status.setCkl(this._blood.getCkl());
				
				creatAshtimer.removeEventListener(TimerEvent.TIMER,Ashman);
				this._appStart._changeFrame(1);		//使本幕架空，一切结束
			}
		}
		
		//鼠标监听
		public function onMouseDown(event:MouseEvent):void{
			if(this.flag==0){
				meattack = new Attack();
				flystestobj.push(meattack.MeStartAttack(this._stage,me.getme()));		//将//Flys1其加入飞镖碰撞检测队列
				flag = 1;
			}
		}
		/*
		public function onMouseUp(event:MouseEvent):void{
			this._stage.removeEventListener(MouseEvent.MOUSE_DOWN,onMouseDown);
		}
		*/
		//键盘监听
		public function onKeyboardEvent(event:KeyboardEvent):void{
			if (event.type=="keyDown"){
				if (keycode.indexOf(event.keyCode)!=-1) {// 已经按过了
					return;
				}
				else{
					keycode.push(event.keyCode);// 没按过，把键存起来
					addEventListener(Event.ENTER_FRAME,onEnterFrame);
				}
			}
			else{	//keyUp
				var tempIndex:int=-1;
				tempIndex=keycode.indexOf(event.keyCode);
				if(tempIndex>0){
					keycode.splice(tempIndex,1);// 按键弹起，从数组里清除
				}
			}
		}
		
		public function onEnterFrame(event:Event):void{	
			//碰撞检测
			flyshittest.flysobjtesting(this._stage,event,enemys,flystestobj,this._appStart); //开始敌人碰撞检测，参数表列：舞台，事件，敌人队列，飞镖队列，主类（含音效）
			flyshittest.flysHurtMeTest(this._stage,event,me,flyshurtmeobj,this._blood);		//开始主角受伤碰撞检测
				
			//如果主角攻击存在且飞镖超出边界，移除忍标 
			if( meattack ){
				var flys1:Flys1 = meattack.getflys1();
				if(flys1){
					if(flag==1){
						if( (flys1.x>=this._stage.stageWidth) || (flys1.y>=this._stage.stageHeight) || (flys1.x<0) || (flys1.y<0) ){
							meattack.removeflys1();
							flys1 = null;
							meattack = null;
							this.flag = 0;
							return;
						}
					}
					var vx:Number = Math.cos(meattack.angle) * meattack.flysspeed;
					var vy:Number = Math.sin(meattack.angle) * meattack.flysspeed;
					flys1.x += vx;
					flys1.y += vy;
				}
			}
			
			//如果敌人攻击存在且飞镖超出边界，移除忍标 ??? 已被上面移除？？
			for(var s=0;s<5;s++){
				if(enemys[s]){	//如果敌人存在
					if(enemys[s].getAttack().getflys2()){	//如果忍标存在
						if( this._stage.contains(enemys[s].getAttack().getflys2()) ){	   //如果在舞台上
							var flys2 = enemys[s].getAttack().getflys2();
							if( (flys2.x>=this._stage.stageWidth+10) || (flys2.y>=this._stage.stageHeight+10) || (flys2.x<0-10) || (flys2.y<0-10) ){	//如果超出了边界
								enemys[s].getAttack().removeflys2();
//								trace("has remove flytestobj" + s);
								flystestobj[s] = null;
							}
						}
					}
				}
			}
			
			//键盘
			for(var k=0;k<keycode.length;k++){
				switch(keycode[k]){
					case 87:if(me.getposy() > 50) {me.changepos("up");break};	//W
					case 83:if(me.getposy() < 770){me.changepos("down");break}; //S
					case 65:if(me.getposx() > 50) {me.changepos("left");break}; //A
					case 68:if(me.getposx() < 980){me.changepos("right");break};//D
					
					case 48:{this._status.setCurrentItem(0);changeItem();break;}		//0
					case 49:{this._status.setCurrentItem(1);changeItem();break;}		//1
					case 52:{this._status.setCurrentItem(4);changeItem();break;}		//4
				}
			}
		}
	}
}